package org.sonar.java.rule.checks.namerules;

import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.tree.BaseTreeVisitor;
import org.sonar.plugins.java.api.tree.*;
import sun.reflect.generics.tree.Tree;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

@Rule(key = "ApplicationConfigCheck")
public class ApplicationConfigCheck extends BaseTreeVisitor implements JavaFileScanner {

    private JavaFileScannerContext context;

    @Override
    public void scanFile(JavaFileScannerContext context) {
        this.context = context;
        // 获取文件路径
        String filePath = this.context.getFile().getPath();

        // 如果是application.yml文件
        if (filePath.endsWith("aplication.properties")) {
            // 执行检查逻辑
            // 你可以在这里调用检查Apollo配置的方法
            try {
                Properties appProps = new Properties();
                appProps.load(new FileInputStream(filePath));

                String apolloServerAddress = appProps.getProperty("apollo.server.address");
                if (apolloServerAddress == null || apolloServerAddress.isEmpty()) {
                    context.reportIssue(this, null, "Apollo server address is missing in application.properties.");
                }
            } catch (Exception e) {
                // 报告读取文件的异常，而不是打印堆栈跟踪
                context.reportIssue(this, null, "Failed to read application.properties file: " + e.getMessage());
            }
        }
    }

    @Override
    public void visitClass(ClassTree tree) {
        // 在这里添加你的自定义规则逻辑
        // 可以使用 tree.symbol() 获取变量相关信息
        super.visitClass(tree);
    }

    @Override
    public void visitLiteral(LiteralTree tree) {
        // 在这里添加你的自定义规则逻辑
        String literalValue = tree.value();
        if (literalValue.contains("apollo")) {
            // 违规，可以发出警告或记录问题

        }
    }
}

